const express = require('express');
const app = express();
const axios = require('axios');
const cors = require('cors');
const { exec,execSync, spawnSync } = require('child_process');
app.use(cors())
app.use(express.json())

// 定义GET API
app.get('/api/ip', (req, res) => {
    res.json({ isOnline: true });
});
app.post('/api/setip', (req, res) => {
    console.log(req.body);
    let isTrue = setWIFI('powershell_script.ps1', true, req.body.ip, req.body.apiurl)
    if(isTrue){
        res.json({ code: 200, msg: "网络连接已切换至 Wi-Fi，并禁用了以太网（5G）。" })
    }else{
        res.json({ code: -1, msg: "执行失败" })
    }

});
app.post('/api/setip5', (req, res) => {
    console.log(req.body);
    let isTrue = setWIFI('powershell_script5.ps1', false, req.body.ip, req.body.apiurl)
    if (isTrue) {
        res.json({ code: 200, msg: "网络连接已切换至以太网（5G），并禁用了 Wi-Fi。" })
    } else {G
        res.json({ code: -1, msg: "执行失败" })
    }

});
function setWIFI(name, isTrue, ip, apiurl) {
    async function switchToWiFi() {
        const powershellPath = name
        const powershellPath2 = "linkWifi.ps1"
        try {
            // 切换网络
            execSync(`powershell -ExecutionPolicy Bypass -File "${powershellPath}"`, { stdio: 'inherit' });
            if(isTrue){
                // 连接WiFi; 
               execSync(`powershell -ExecutionPolicy Bypass -File "${powershellPath2}"`, { stdio: 'inherit' });
            }
            setipFn(apiurl, ip)
            console.log('执行成功');
            return true
        } catch (error) {
            console.error(`执行 PowerShell 命令时发生错误： ${error.message}`);
            if (error.status) {
                console.error(`错误状态码： ${error.status}`);
            }
        } 
    }
    // 执行切换操作
    let res =  switchToWiFi();
    if(res){
        
        return true
    }else{
        return false
    }
}

function setipFn(apiurl,ip){
    // 修改ip,
    console.log("修改ip",apiurl)
    let command;// 定义要执行的命令
    if (apiurl == "setip") {
        console.log(apiurl)
        command = `netsh interface ip set address "WALN" static ${ip} 255.255.255.0 192.168.1.1`;
    } else if (apiurl == "setip5") {
        command = `netsh interface ip set address "以太网" static ${ip} 255.255.255.0 192.168.1.1`;
    }
    // 使用child_process模块执行命令
    exec(command, (error, stdout, stderr) => {
        if (error) {
            console.error(`执行命令时发生错误: ${error.message}`);
            return;
        }
        if (stderr) {
            console.error(`命令执行结果含有错误信息: ${stderr}`);
            return;
        }
        console.log(`命令执行成功，输出结果为: ${stdout}`);
    });
}

const port = 3333;
// 启动服务
app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});
